package com.itboye.ihomebank.activity.hetong;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.gson.Gson;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.activity.qianyue.fragment.OrderFragment;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.bean.HeTongBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.ZhiMaBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.XScrollView;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.HuaBanView;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SaveViewUtil;
import com.itboye.ihomebank.util.UIAlertView;
import com.itboye.ihomebank.util.UploadImage;
import com.itboye.ihomebank.util.UploadImage.OnUploadlistener;
import com.itboye.ihomebank.util.dialog.RxDialogSureCancel;
import com.itboye.ihomebank.web.WebActivity;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

/**
 * 签名
 */
public class ActivityHuaBan extends BaseOtherActivity implements Observer {
    View v_statusbar;
    HuaBanView huaban;
    String fileName = "";
    ImageView close_icon;
    TextView add_shap_title_tv;
    Button ok, reset;
    private UserPresenter userPresenter;
    private String contractNo;
    private String jsonStr;
    private String uid;
    private List<HeTongBean> datas;
    protected String imgId;

    RelativeLayout fenqi;
    boolean isFenQi = false;//是否是分期合同,默认不是
    ToggleButton toggle_button;
    boolean isExpand = false;

    TextView tv_hetong;
    public static File rootDir = new File(
            Environment.getExternalStorageDirectory() + File.separator
                    + "huaban/");
    private Calendar current = Calendar.getInstance(Locale.CHINA);

    XScrollView xScrollView;
    LinearLayout layout_xinxi;//填写个人信息的地方，如果是分期合同，需要填写个人信息
    EditText huaban_age,huaban_sex,huaban_xueli,huaban_adress,huaban_email,huaban_danwei;

    String url,biz_no;
    private UIAlertView uiAlertView;

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.tv_hetong:
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra(
                        "url",
                        NetPublicConstant.WEB_URL02
                                + "/contract/stageagreement?contract_no="
                                + contractNo
                                +"&uid="
                                + (SPUtils.get(this, null,SPContants.USER_ID, "") + "")
                                + "&psw="
                                + (SPUtils.get(this, null,SPContants.PASSWORD, "") + ""));
                intent.putExtra("title", "分期协议");
                startActivity(intent);
                break;
            case R.id.reset:
                huaban.clearScreen();
                break;
            case R.id.toggle_button:
                isExpand = !isExpand;
                if (isExpand){
                    uiAlertView = new UIAlertView(this, "去芝麻认证？", "", "取消", "去认证");
                    uiAlertView.show();
                    uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                        @Override
                        public void doLeft() {
                            uiAlertView.dismiss();
                        }
                        @Override
                        public void doRight() {
                            uiAlertView.dismiss();
                            doVerify(url);
                        }
                    });
                }
                break;
            case R.id.ok:
                if (isFenQi == true) {
                    if (isExpand == false) {
                        ByAlert.alert("你还没有同意住家租房分期借款协议");
                        return;
                    }
                    if (huaban_age.getText().toString().equals("")||huaban_sex.getText().toString().equals("")||huaban_xueli.getText().toString().equals("")||
                            huaban_adress.getText().toString().equals("")||huaban_email.getText().toString().equals("")||huaban_danwei.getText().toString().equals("")){
                        ByAlert.alert("请填写完整个人信息");
                        return;
                    }
                }
                showProgressDialog("签名上传中,请稍后", false);
                Long currentMil = System.currentTimeMillis();
                if (SaveViewUtil.saveScreen(huaban, currentMil)) {
                    UploadImage.getInstance().execute(
                            new String[]{rootDir.getAbsolutePath() + "/"
                                    + currentMil + ".jpg"}, "signature",
                            new OnUploadlistener() {

                                @Override
                                public void OnSuccess(
                                        ArrayList<AvatarDataBeans> resultData) {
                                    // TODO Auto-generated method stub
                                    try {
                                        closeProgressDialog();
                                    } catch (Exception e) {
                                        // TODO: handle exception
                                    }
                                    imgId = resultData.get(0).getId();
                                    ByAlert.alert("签名已上传");
                                    if (contractNo != null) {
                                        buildJson();// 生成json数据
                                    } else {
                                        Intent intent = new Intent();
                                        intent.putExtra("imgId", imgId);
                                        setResult(108, intent);
                                        finish();
                                    }
                                }
                                @Override
                                public void OnError(String resultData) {
                                    // TODO Auto-generated method stub
                                    ByAlert.alert(resultData);
                                }
                            }, null);
                } else {
                    Toast.makeText(this, "保存失败，请检查sdcard是否可用", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 启动支付宝进行认证
     * @param url 开放平台返回的URL
     */
    private void doVerify(String url) {
        if (hasApplication()) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            // 这里使用固定appid 20000067
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivityForResult(action, 101);
        } else {
            // 处理没有安装支付宝的情况
            new AlertDialog.Builder(this)
                    .setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        }
    }
    /**
     * 判断是否安装了支付宝
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101) {
            userPresenter.zhiMaChaXun(SPUtils.get(this, null, SPContants.USER_ID, "") + "",biz_no);
        }
    }
    protected void buildJson() {
        // TODO Auto-generated method stub
        if (contractNo != null) {
            if (datas == null) {
                ByAlert.alert("合同参数有误");
            } else {
                HashMap<String, String> hashMap = new HashMap<>();
                for (Iterator iterator = datas.iterator(); iterator.hasNext(); ) {
                    HeTongBean heTongBean = (HeTongBean) iterator.next();
                    if (heTongBean.getKey().equals("sign_renter_date")) {
                        hashMap.put(heTongBean.getKey(), current.get(Calendar.YEAR) + "-" + (current.get(Calendar.MONTH) + 1) + "-" + current.get(Calendar.DATE) + "");
                    } else if (heTongBean.getKey().equals("phone_renter")) {
                        hashMap.put(heTongBean.getKey(),
                                heTongBean.get_default());
                    } else if (heTongBean.getKey().equals("sign_renter")) {
                        hashMap.put(heTongBean.getKey(), imgId);
                    }
                }
                hashMap.put("age", huaban_age.getText().toString());
                hashMap.put("sex", huaban_sex.getText().toString());
                hashMap.put("education", huaban_xueli.getText().toString());
                hashMap.put("used_address", huaban_adress.getText().toString());
                hashMap.put("email", huaban_email.getText().toString());
                hashMap.put("company", huaban_danwei.getText().toString());

                Gson gson = new Gson();
                jsonStr = gson.toJson(hashMap);
                uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
                userPresenter.tiJiaoHeTong(uid, contractNo, jsonStr);
            }
        }
    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_huabanqianming;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onInit() {
        // TODO Auto-generated method stub
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("填写签名");
        contractNo = getIntent().getStringExtra("contractNo");
        if (contractNo != null) {// 租客填写
            userPresenter = new UserPresenter(this);
            showProgressDialog("正在获取合同参数...",true);
            userPresenter.heTongParams("1", contractNo);

            userPresenter.zhiMa(SPUtils.get(this, null, SPContants.USER_ID, "") + "");
        }
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.heTongParams_success) {
                datas = (List<HeTongBean>) entity.getData();
                for (int i = 0; i < datas.size(); i++) {
                    HeTongBean bean = datas.get(i);
                    if (bean.getKey().equals("stage")) {
                        isFenQi = true;
                        break;
                    }
                }
                if (isFenQi == true) {//是否是分期合同
                 //   userPresenter.zhiMa(SPUtils.get(this, null, SPContants.USER_ID, "") + "");

                    fenqi.setVisibility(View.VISIBLE);
                    layout_xinxi.setVisibility(View.VISIBLE);
                    xScrollView.setVisibility(View.VISIBLE);
                } else {
                    fenqi.setVisibility(View.GONE);
                    layout_xinxi.setVisibility(View.GONE);
                    xScrollView.setVisibility(View.GONE);
                }
            } else if (entity.getEventType() == UserPresenter.heTongParams_fail) {

            } else if (entity.getEventType() == UserPresenter.heTongTiJiao_success) {
                Intent intent = new Intent();
                intent.putExtra("shenfen", "renter");
                intent.putExtra("contractNo", contractNo);
                sendBroadcast(intent);
                OrderFragment.getInstance().refresh();
                ByAlert.alert(entity.getData());
                final RxDialogSureCancel dialog = new RxDialogSureCancel(ActivityHuaBan.this,"确认合同","确认合同后，房东将不能再修改合同","确认","查看合同");//提示弹窗
                dialog.getSureView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.cancel();
                        userPresenter.wanChengHeTong(uid, contractNo);

                    }
                });
                dialog.getCancelView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        dialog.cancel();
//                        finish();
                        Intent intent = new Intent(ActivityHuaBan.this, WebActivity.class);
                        intent.putExtra("url", NetPublicConstant.HETONG_URL
                                + "?uid=" + uid + "&psw=" + SPUtils.get(ActivityHuaBan.this, null, SPContants.PASSWORD, "") + ""
                                + "&contract_no=" + contractNo + "&pc=1");
                        intent.putExtra("title", "查看合同");
                        startActivity(intent);
                    }
                });
                dialog.show();

            } else if (entity.getEventType() == UserPresenter.heTongTiJiao_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.zhima_success) {
                ZhiMaBean bean= (ZhiMaBean) entity.getData();
                url=bean.getUrl();
                biz_no = bean.getBiz_no();
            } else if (entity.getEventType() == UserPresenter.zhima_fail) {
//                ByAlert.alert(entity.getData());
            }
            else if (entity.getEventType() == UserPresenter.zhima_save_success) {
//                ByAlert.alert(entity.getData());
            }
            else if (entity.getEventType() == UserPresenter.zhima_save_fail) {
                ByAlert.alert(entity.getData());
            }else
            if (entity.getEventType() == UserPresenter.queRenHeTong_success) {
                ByAlert.alert(entity.getData());
                finish();
            } else if (entity.getEventType() == UserPresenter.queRenHeTong_fail){
                ByAlert.alert(entity.getData());
                finish();
            }
        }
        try {
            closeProgressDialog();
        }catch (Exception e){

        }
    }

}
